package com.cn;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/5/28
 */

public class TestController {

    public static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {

        /**
         * 主线程线程的ThreadLocal值
         */
        TestController.threadLocal.set("123");
        String s = TestController.threadLocal.get();
        System.out.println("当前线程的ThreadLocal值为：" + s);
        System.out.println("当前线程为：" + Thread.currentThread().getName());


        /**
         * 启动一个新线程
         */
        MyThread myThread = new MyThread();
        myThread.setName("线程1");
        myThread.start();


        /**
         * 第一个线程池中各线程的ThreadLocal值
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("第一个线程"));
        for (int i = 0; i < 5; i++) {
            threadPoolExecutor.execute(() -> {
                TestController.threadLocal.set(Thread.currentThread().getName());
                System.out.println("当前线程的ThreadLocal值为：" + TestController.threadLocal.get());
            });
        }
        threadPoolExecutor.shutdown();


        /**
         * 第二个线程池中各线程的ThreadLocal值
         */
        ThreadPoolExecutor threadPoolExecutorTwo = new ThreadPoolExecutor(5, 10, 60, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("第二个线程"));

        for (int i = 0; i < 5; i++) {
            threadPoolExecutorTwo.execute(() -> {
                TestController.threadLocal.set(Thread.currentThread().getName());
                System.out.println("当前线程的ThreadLocal值为：" + TestController.threadLocal.get());
            });
        }
        threadPoolExecutorTwo.shutdown();


    }
}
